using UnityEngine;
using System.Collections;

public class SmoothFollow : MonoBehaviour
{
	
	float XOffsetDamping = 1.0f;
	public Transform target;
	public Transform leftPoint;
	public Transform rightPoint;
	
	public Vector3 balanceDirection{
		get{return direction;}
	}
	
	public bool cameraIsMoving{
		get{return isMoving;}
	}
	
	//ToDelete
	public Vector3 v;
	
	PlayerAction action;
	Transform trans;
	float currentX;
	float wantedX;
	InputInfo inputInfo;
	bool isBorder = false;
	Vector3 targetPosition;
	Vector3 position;
	float leftBorder;
	float rightBorder;
	Vector3 direction = Vector3.zero;
	bool isMoving;
	Vector3 prePosition;
	
	public bool IsBorder {
		get{ return isBorder;}
	}
	
	void  Start ()
	{
		if (target == null)
			target = PlayerData.Instance().MainRoleInstance.transform;
		action = target.GetComponent<PlayerAction> ();
		
		inputInfo = GetComponent<InputInfo> ();
		trans = transform;
		
		leftBorder = leftPoint.position.x;
		rightBorder = rightPoint.position.x;
		targetPosition = trans.position;
		
		XOffsetDamping = action.speed;
	}
	
	void LateUpdate ()
	{
		if(inputInfo.hasSingleTouch == false && action.IsIdling == true){
			isMoving = false;
			if(Vector3.Distance(targetPosition,action.transform.position) < 0.001f){
				return;
			}
		}
		
		targetPosition = action.targetPoint;
		
		if(trans.position.x <= leftBorder || trans.position.x >= rightBorder){
			isBorder = true;
			action.speed = XOffsetDamping;
		} else {
			isBorder = false;
		}
		
		if(isBorder){
			v = targetPosition;
			if((targetPosition.x <= leftBorder || targetPosition.x >= rightBorder) && !GameDefine.Click_Task_One){
				isMoving = false;
				return;
			} else if(trans.position.x <= leftBorder){
				if(trans.position.x - target.position.x > 0.001f){
					return;
				}
			} else if(trans.position.x >= rightBorder){
				if(target.position.x - trans.position.x > 0.001f){
					return;
				}
			}
		}
		
		
		float x = Mathf.Abs(inputInfo.Hit.point.x - target.position.x);
		float y = Mathf.Abs(inputInfo.Hit.point.y - target.position.y);
		float speed = XOffsetDamping * y / x;
		action.speed = (speed > XOffsetDamping) ? XOffsetDamping : speed;
		
		targetPosition.z = trans.position.z;
		targetPosition.y = trans.position.y;
		
		
		if(Mathf.Abs(trans.position.x - targetPosition.x) < 0.0001f){
			isMoving = false;
		} else {
			trans.position = Vector3.MoveTowards(trans.position,targetPosition,XOffsetDamping * Time.deltaTime);
			isMoving = true;
		}
		
		direction = trans.position - prePosition;
		direction.z = 0;
		direction.y = 0;
		
		/*
		position = trans.localPosition;
		position.x = Mathf.Round(position.x);
		trans.localPosition = position;
		*/
		prePosition = trans.position;
		
	}
}
